package com.yayako.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yayako.result.Result;
import com.yayako.result.ResultFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.yayako.result.ResultCode.FORBIDDEN;

@Component
public class AuthAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        Result result = ResultFactory.buildResult(FORBIDDEN,"权限不足，无法访问！",null);
        PrintWriter out = httpServletResponse.getWriter();
        ObjectMapper om = new ObjectMapper();
        out.write(om.writeValueAsString(result));
    }
}
